<template>
	<view class="pay-page">
		<bnn-loading :loading="isLoading"/>
		<scroll-view class="pay-body">
			<view class="time-select">
				<view class="section-title">选择订阅时长</view>
				<view class="price-list d-f j-c-b f-w-w">
					<view v-for="(item, key) in priceList" :key="key" class="price" :class="{'active': priceInfo.id === item.id}" @click="switchPayTime(item, key)">
						<view class="pay-amount">
							<view class="month">{{item.effective_time}}个月</view>
							<view class="cash">￥{{item.price * item.effective_time}}</view>
						</view>
						<view class="cash-monthly">
							<view class="yuan">￥</view>
							<view class="amount">{{item.price}}</view>
							<view class="unit">/月</view>
						</view>
						<view class="origin-price">原价￥{{item.original_price * item.effective_time}}</view>
						<view class="slw-icon select-icon">&#xe6a6;</view>
					</view>
				</view>
			</view>
			<view class="option-list">
				<view class="list-item" @click="setOpenCoupon(true)">
					<view class="item-left">优惠券</view>
					<view class="item-right d-f a-i-c">
						<view class="coupon-name">{{couponInfo.name}}</view>
						<view class="slw-icon">&#xe733;</view>
					</view>
				</view>
			</view>
			<view class="pay-method">
				<view v-for="(type, key) in typeList" :key="key" class="method" @click="switchPayType(key)">
					<view class="h-line"/>
					<view class="method-info">
						<view class="method-left">
							<view class="slw-icon method-icon alipay" style="color: 0d99f3;" v-html="type.icon"/>
							<view>{{type.name}}</view>
						</view>
						<view class="method-right">
							<view class="slw-icon select-icon" :class="{'active': typeKey === key}">&#xe656;</view>
							<view class="slw-icon select-icon" :class="{'active': typeKey !== key}">&#xe6d7;</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="pay-foot">
			<view class="h-line"/>
			<view class="foot-body d-f j-c-b">
				<view class="total d-f a-i-c">
					<view class="total-amount">￥{{payAmount}}</view>
				</view>
				<view class="btn-subscribe d-f a-i-c j-c-c" @click="onPayNow">立即支付</view>
			</view>
		</view>
		<bnn-float-layout :isShow="isOpenCoupon" scrollY title='优惠券' class="coupon-float" @close="setOpenCoupon(false)">
			<view class="coupon-list">
				<view v-for="(coupon, key) in couponList" :key="key" class="coupon-item" @click="onClickCoupon(coupon)">
					<view class="coupon">
						<view class="coupon-left">
							<image v-if="payAmount >= coupon.min_order_amount" src="https://sou-liang.oss-cn-shanghai.aliyuncs.com/weixin/images/my_coupon_active.png" class="coupon-img"/>
							<image v-else src="https://sou-liang.oss-cn-shanghai.aliyuncs.com/weixin/images/my_coupon.png" class="coupon-img"/>
							<view class="left-content">
								<view class="price">
									<view class="price-unit">￥</view>
									<view class="price-num">{{coupon.amount}}</view>
								</view>
							</view>
						</view>
						<view class="coupon-right">
							<view class="coupon-name">{{coupon.name}}</view>
							<view class="h-line"/>
							<view class="time">
								<view class="time-left">{{coupon.expire_time | parseTime('YYYY-MM-DD')}}</view>
								<view class="time-status active">立即使用</view>
							</view>
						</view>
					</view>
				</view>
				<coupon-empty v-if="couponList.length === 0"/>
			</view>
		</bnn-float-layout>
	</view>
</template>

<script>
	import calc from '@/utils/calc.js'
	import lodash from '@/utils/lodash.js'
	import { getCouponList, createOrder, getPaySdk } from '@/api/trade.js'
	import { getStrategyInfo } from '@/api/strategy.js'
	import BnnFloatLayout from '@/components/bnn-ui/float-layout/index.vue'
	import CouponEmpty from '@/components/data-empty/coupon.vue'
	import BnnLoading from '@/components/bnn-ui/loading/index.vue'
	import { toUserStrategyPage } from '@/utils/PageRouter.js'
	
	export default {
		components: { BnnFloatLayout, CouponEmpty, BnnLoading },
		data() {
			return {
				id: '',
				isLoading: true,
				strategy: {},
				isOpenCoupon: false,
				price: 1,
				loading: false,
				providerList: [],
				payAmount: 0,
				couponInfo: {},
				couponList: [],
				typeKey: 0,
				typeList: [
					{ id: 'alipay', value: 'ALI_PAY', name: '支付宝支付', icon: '&#xe618;' },
					{ id: 'wxpay', value: 'WECHAT_PAY', name: '微信支付', icon: '&#xe622;' }
				],
				priceInfo: {},
				priceList: [],
			}
		},
		onLoad (options) {
			this.id = options.id
			this.getStrategy(options.id)
			// #ifdef APP-PLUS
			this.getPayType()
			// #endif
			this.getCoupons()
		},
		methods: {
			//	获取策略信息
			getStrategy (id) {
				getStrategyInfo({ id }).then(res => {
					const { data } = res
					const priceList = data.priceList.map(item => {
						item.price = calc.Div(item.price, 100)
						item.original_price = calc.Div(item.original_price, 100)
						item.amount = calc.Mul(item.effective_time, item.price)
						return item
					})
					const priceInfo = lodash.head(priceList)
					this.strategy = data
					this.priceInfo = priceInfo
					this.priceList = priceList
					this.payAmount = this.calcPayAmount(priceInfo)
					setTimeout(() => {
						this.isLoading = false
					}, 500)
				})
			},
			//	获取支付方式
			getPayType () {
				uni.getProvider({
					service: "payment",
					success: (e) => {
						let typeList = []
						e.provider.map((id) => {
							switch (id) {
								case 'alipay':
									typeList.push({id: id, value: 'ALI_PAY', name: '支付宝支付', icon: '&#xe618;'})
									break
								case 'wxpay':
									typeList.push({id: id, value: 'WECHAT_PAY', name: '微信支付', icon: '&#xe622;'})
									break
								default:
									break
							}
						})
						this.typeList = typeList
					},
					fail: (e) => {
					}
				})
			},
			//	获取可使用的优惠券
			getCoupons () {
				getCouponList({ status: 0 }).then(res => {
					this.couponList = res.data
				})
			},
			//	(打开、关闭)优惠券弹窗
			setOpenCoupon(bool) {
				this.isOpenCoupon = bool
			},
			//	选择优惠券
			onClickCoupon(coupon) {
				const { payAmount, priceInfo } = this
				if (payAmount >= coupon.min_order_amount) {
					this.setOpenCoupon(false)
					this.couponInfo = coupon
					this.payAmount = this.calcPayAmount(priceInfo)
				}
			},
			//	计算支付金额
			calcPayAmount (time) {
				const { couponInfo } = this
				let amount = calc.Mul(time.effective_time, time.price)
				if (couponInfo.amount) {
					amount = calc.Sub(amount, couponInfo.amount)
				}
				return (amount >= 0 ? amount : 0)
			},
			//	切换支付方式
			switchPayType (key) {
				this.typeKey = key
			},
			//	切换购买时长
			switchPayTime (item, key) {
				this.priceInfo = item
				const { couponInfo, payAmount } = this
				this.couponInfo = (item.amount >= couponInfo.min_order_amount) ? couponInfo : {}
				this.payAmount = this.calcPayAmount(item)
			},
			//	立即付款
			onPayNow (){
				const { typeKey, typeList } = this
				const type = typeList[typeKey]
				uni.showLoading({ title: '加载中', mask: true })
				this.createOrder()
				// this.requestPayment(typeList[typeKey], typeKey)
			},
			//	创建订单
			createOrder () {
				const { id, couponInfo, priceInfo, typeKey, typeList, payAmount } = this
				const pay_type = typeList[typeKey]
				createOrder({
					pay_type: pay_type.id,
					strategy_id: id,
					strategy_price_id: priceInfo.id,
					discount_card_id: couponInfo.id
				}).then(res => {
					const { data } = res
					uni.hideLoading()
					if (data.isNeedPay) {
						const { aliPay } = res.data
						this.weixinPay(aliPay)
						
						// this.requestPayment(pay_type, payAmount)
						// if (pay_type.value === 'ALI_PAY') {
						// 	this.requestPayment(pay_type, payAmount)
						// } else {
						// 	this.weixinPay()
						// }
						
						// uni.requestPayment({
						// 	provider: pay_type.id,
						// 	orderInfo: data.aliPay,
						// 	success: () => {
						// 		uni.hideLoading()
						// 		uni.showToast({ title: "订阅成功！" })
						// 		setTimeout(() => {
						// 			toUserStrategyPage(true)
						// 		}, 500)
						// 	},
						// 	fail: e => {
						// 		uni.hideLoading()
						// 		uni.showModal({
						// 			content: `支付失败,原因为: ${e.errMsg}`,
						// 			showCancel: false
						// 		})
						// 	}
						// })
					} else {
						uni.showToast({ title: "订阅成功！" })
						setTimeout(() => {
							toUserStrategyPage(true)
						}, 500)
					}
				}).catch(err => {
					uni.hideLoading()
				})
			},
			weixinPay(aliPay) {
				uni.getProvider({
					service: 'payment',
					success: ({ provider }) => {
						if (~provider.indexOf('wxpay')) {
							const number = Number(new Date())
							uni.requestPayment({
								provider: 'wxpay',
								// timeStamp: (number + '').substr(0, 10),
								// nonceStr: aliPay.nonce_str,
								// package: "Sign=WXPay",
								// signType: "MD5",
								// paySign: aliPay.sign,
								// orderInfo: JSON.stringify({
								// 	appid: aliPay.appid,
								// 	noncestr: aliPay.nonce_str,
								// 	package: "Sign=WXPay",
								// 	partnerid: aliPay.mch_id,
								// 	prepayid: aliPay.prepay_id,
								// 	timestamp: (number + '').substr(0, 10),
								// 	sign: aliPay.sign
								// }),
								// "appid": "wxxxxxxxxxxxxx",
								// "noncestr": "84FB3E2B75B04343921985C4DB75BC45",
								// "package": "Sign=WXPay",
								// "partnerid": "000000000",
								// "prepayid": "wx1514411xxxxxxxxxxxxxxxxxx699386300",
								// "sign": "62FD6A3EF48CE76AFD2XXB0D9C70EEDD",
								// "timestamp": "1594795179"
								orderInfo: JSON.stringify({
									"appid": aliPay.appid,
									"noncestr": aliPay.nonce_str,
									"package": "Sign=WXPay",
									"partnerid": aliPay.mch_id,
									"prepayid": aliPay.prepay_id,
									"timestamp": "1598080242",
									"sign": aliPay.sign,
								}),
								success(res) {
									// res
								},
								fail(err) {
									// err
								}
							})
						}
					}
				})
			},
			async requestPayment(e, total) {
				getPaySdk({ payid: e.id, total }).then(res => {
					// uni.requestPayment({
					// 	provider: e.id,
					// 	orderInfo: res.data,
					// 	success: (e) => {
					// 		uni.hideLoading()
					// 		uni.showToast({
					// 			title: "感谢您的赞助!"
					// 		})
					// 	},
					// 	fail: (e) => {
					// 		uni.hideLoading()
					// 		uni.showModal({
					// 			content: "支付失败,原因为: " + e.errMsg,
					// 			showCancel: false
					// 		})
					// 	}
					// })
				}).catch(err => {
					uni.hideLoading()
					if (orderInfo.statusCode !== 200) {
						uni.showModal({ content: "获得订单信息失败", showCancel: false })
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.pay-page{
		/* #ifdef APP-PLUS */
		height: 100vh;
		/* #endif */
		
		/* #ifndef APP-PLUS */
		height: calc(100vh - var(--window-top));
		/* #endif */
		position: relative;
		.coupon-float /deep/{
			.b-f-l__container{border-radius: 24rpx 24rpx 0 0;background-color: $theme_bg_color;}
			.layout-header{background-color: $theme_bg_color;}
			.coupon-list{
				.coupon-item{
					margin-bottom: 20rpx;
					&:last-child{
						margin-bottom: 0;
					}
				}
			}
		}
		.pay-body{
			width: 100%;
			height: 100%;
			.time-select{
				background: #fff;
				padding: 0 16px 10px;
				margin-bottom: 10px;
				.section-title{
					color: #666;
					padding: 30rpx 0 20rpx;
				}
				.price-list{
					.price{
						width: 47.5%;
						height: 180rpx;
						border: 1rpx solid #f0f0f0;
						padding: 20rpx 0;
						display: flex;
						position: relative;
						align-items: center;
						border-radius: 4rpx;
						margin-bottom: 30rpx;
						flex-direction: column;
						justify-content: center;
						.pay-amount{
							display: flex;
						}
						.month{
							padding-right: 10rpx;
						}
						.cash-monthly{
							color: #fe6b4f;
							display: flex;
							align-items: baseline;
							line-height: 64rpx;
						}
						.amount{
							font-size: 48rpx;
							padding-right: 10rpx;
						}
						.origin-price{
							color: #999;
							font-size: 20rpx;
							text-decoration: line-through;
						}
						.select-icon{
							color: #ff9954;
							display: none;
							font-size: 48rpx;
							position: absolute;
							right: -2rpx;
							bottom: -2rpx;
						}
					}
					.price.active{
						border-color: #ff9954;
						background: #fff6ef;
						.select-icon{
							display: block;
						}
					}
				}
			}
			
			.option-list{
				margin-bottom: 20rpx;
				.list-item{
					height: 100rpx;
					padding: 0 30rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					background-color: #fff;
				}
			}
			
			.pay-method{
				background-color: #fff;
				.method{
					&:nth-child(1) .method-icon{color: #0d99f3;}
					&:nth-child(2) .method-icon{color: #41b141;}
				}
				.method-info{
					height: 120rpx;
					padding: 0 30rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					.method-left{
						display: flex;
						align-items: center;
					}
					.method-icon{
						font-size: 64rpx;
						margin-right: 30rpx;
					}
					.select-icon{
						color: #d2d1d1;
						color: $theme_color;
						display: none;
						font-size: 50rpx;
					}
					.active{
						display: block;
					}
				}
			}
		}
		
		.pay-foot{
			width: 100%;
			position: absolute;
			bottom: 0;
			background-color: #fff;
		}
		.foot-body{
			height: 100rpx;
			.total{
				padding-left: 40rpx;
				.total-amount{
					color: #ff6600;
					font-size: 40rpx;
				}
			}
			.btn-subscribe{
				color: #fff;
				padding: 0 80rpx;
				background-color: $theme_color;
			}
		}
	}
	
	
	.coupon{
		width: 100%;
		height: 170rpx;
		display: flex;
		.coupon-left{
			width: 240rpx;
			position: relative;
			.coupon-img{
				width: 240rpx;
				height: 170rpx;
			}
			.left-content{
				top: 0;
				left: 0;
				height: 100%;
				width: 100%;
				position: absolute;
				display: flex;
				align-items: center;
				justify-content: center;
			}
			.price{
				color: #fff;
				display: flex;
				align-items: baseline;
				.price-unit{
					font-size: 32rpx;
					line-height: 1;
					font-weight: bold;
				}
				.price-num{
					font-size: 56rpx;
					line-height: 1;
					font-weight: bold;
				}
			}
		}
		.coupon-right{
			flex: 1;
			height: 100%;
			display: flex;
			flex-direction: column;
			padding-left: 20rpx;
			background-color: #fff;
			.coupon-name{
				flex: 1;
				display: flex;
				align-items: center;
			}
			.time{
				padding: 20rpx 20rpx 20rpx 0;
				display: flex;
				align-items: center;
				justify-content: space-between;
			}
			.time-left{
				color: #999;
				display: flex;
				font-size: 24rpx;
			}
			.time-status{
				color: #fff;
				width: 132rpx;
				height: 40rpx;
				font-size: 22rpx;
				border-radius: 100rpx;
				background-color: #cecece;
				display: flex;
				align-items: center;
				justify-content: center;
			}
			.time-status.active{
				background-color: $theme_color;
			}
		}
	}
</style>
